package com.dmall.play.interview.chapter07;

import java.util.ArrayList;
import java.util.List;

public class Leetcode230V2 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private int ans;
    private int count;

    public int kthSmallest(TreeNode root, int k) {
        inOrder(root, k);
        return ans;
    }

    private void inOrder(TreeNode node, int k) {
        if (node == null) {
            return;
        }
        inOrder(node.left, k);
        count ++;
        if (count == k) {
            ans = node.val;
        } else {
            inOrder(node.right, k);
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(1);
        root.right = new TreeNode(4);
        root.left.right = new TreeNode(2);
        Leetcode230V2 leetcode230 = new Leetcode230V2();
        System.out.println(leetcode230.kthSmallest(root, 3));
    }
}
